package com.lemon.smartsafety.ui.fragment.safe.inspection;

import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ldzs.recyclerlibrary.Mode;
import com.ldzs.recyclerlibrary.PullToRefreshRecyclerView;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.app.RefreshType;
import com.lemon.smartsafety.entity.event.datacoll.BuildingCheckItemRefreshEvent;
import com.lemon.smartsafety.entity.event.datacoll.BuildingPositionRefreshEvent;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.entity.event.inspection.InspectionCheckItemViewDetailEvent;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingCheckItemExistVo;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingCheckItemVo;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingIndexVo;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingItemCountVo;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingVo;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.http.service.SafeDataServices;
import com.lemon.smartsafety.listener.PullRefreshListener;
import com.lemon.smartsafety.listener.RecyclerTClickListener;
import com.lemon.smartsafety.ui.activity.safe.inspection.CheckItemDetailActivity;
import com.lemon.smartsafety.ui.activity.safe.inspection.SafeInspectionStepOneActivity;
import com.lemon.smartsafety.ui.adapter.safe.inspection.BuildingInspectionCheckItemAdapter;
import com.lemon.smartsafetynew.ui.fragment.base.BaseFragment;
import com.lemon.smartsafety.utils.LogUtils;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafety.view.list.MultiStateView;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import kale.adapter.LemonRcvAdapter;

/**
 * 项目名称：workspace
 * 类描述：
 * 创建人：Fargo
 * 创建时间：2016/9/2 16:03
 * 修改人：Fargo
 * 修改时间：2016/9/2 16:03
 * 修改备注：
 */
public class CheckItemNewListFragment extends BaseFragment implements PullRefreshListener, RecyclerTClickListener<CompanyBuildingCheckItemVo> {
    @Bind(R.id.top_line)
    View topLine;
    @Bind(R.id.tv_tip)
    TextView tvTip;
    @Bind(R.id.ll_position)
    LinearLayout llPosition;
    @Bind(R.id.swipe_layout)
    SwipeRefreshLayout swipeLayout;
    @Bind(R.id.float_button)
    FloatingActionButton floatButton;
    @Bind(R.id.mRefreshContainer)
    LinearLayout mRefreshContainer;
    private LoggerHelper loggerHelper = new LoggerHelper(CheckItemNewListFragment.class);


    @Bind(R.id.pullToRefreshRecyclerView)
    public PullToRefreshRecyclerView mPullToRefreshRecyclerView;

    @Bind(R.id.multiStateView)
    public MultiStateView mMultiStateView;


    protected int currentPage = Constants.DEFAULT_FIRST_PAGE_NUMBER;

    protected int pageSize = Constants.PAGE_SIZE;

    public List<CompanyBuildingCheckItemVo> mDataList = new ArrayList<>();

    protected LemonRcvAdapter<CompanyBuildingCheckItemVo> mAdapter;


    /**
     * bundle info
     */
    private CompanyBuildingVo mCompanyBuildingVo;
    private CompanyBuildingIndexVo mCompanyBuildingIndexVo;
    private CompanyBuildingItemCountVo mCompanyBuildingItemCountVo;

    public static CheckItemNewListFragment newInstance() {
        return new CheckItemNewListFragment();
    }


    private String mKeyWord = "";

    protected void getBaseArguments() {
        if (getArguments() != null) {
            mKeyWord = StringUtils.nullValue(getArguments().getString(BundleKey.KEY_WORD));
            mCompanyBuildingVo = (CompanyBuildingVo) getArguments().getSerializable(BundleKey.COMPANY_BUILD_INFO);
            mCompanyBuildingIndexVo = (CompanyBuildingIndexVo) getArguments().getSerializable(BundleKey.COMPANY_BUILDING_INDEX_VO);
            mCompanyBuildingItemCountVo = (CompanyBuildingItemCountVo) getArguments().getSerializable(BundleKey.COMPANY_BUILDING_ITEM_COUNT);
        }

    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_checkitem_newlist;
    }

    @Override
    protected void initViews() {
        pageSize = Integer.MAX_VALUE;//这样设置一下，就不就有加载更多了
        LinearLayoutManager layoutManager = new LinearLayoutManager(IApplication.context(), LinearLayoutManager.VERTICAL, false);
        mPullToRefreshRecyclerView.setRefreshMode(Mode.DISABLED);
        mPullToRefreshRecyclerView.setLayoutManager(layoutManager);
        mAdapter = getLemonAdapter();
        mPullToRefreshRecyclerView.setAdapter(mAdapter);
   /*     mPullToRefreshRecyclerView.setOnPullUpToRefreshListener(new PullToRefreshRecyclerView.OnPullUpToRefreshListener() {
            @Override
            public void onRefresh() {
                currentPage = Constants.DEFAULT_FIRST_PAGE_NUMBER;
                onPullRefresh();
            }
        });*/

        initSwipRefresh();
        mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_END);
        onPullRefresh();
        //mPullToRefreshRecyclerView.addOnScrollListener(onScrollListener);

        //mPullToRefreshRecyclerView.beginRefreshing();

        initGalleryFinalImageLoader();


    }


    private void initSwipRefresh() {

        swipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);


        swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        LogUtils.LOGE("下拉刷新");

                        currentPage = Constants.DEFAULT_FIRST_PAGE_NUMBER;
                        onPullRefresh();
                        swipeLayout.setRefreshing(false);
                    }
                }, 1000);
            }
        });

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mPullToRefreshRecyclerView != null && onScrollListener != null) {
            mPullToRefreshRecyclerView.removeOnScrollListener(onScrollListener);
        }
        ButterKnife.unbind(this);
    }


    public LemonRcvAdapter<CompanyBuildingCheckItemVo> getLemonAdapter() {
        return new BuildingInspectionCheckItemAdapter(mDataList, this);
    }

    private RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            /* 有问题线取消
            LinearLayoutManager manager       = (LinearLayoutManager) recyclerView.getLayoutManager();
            int                 first         = manager.findFirstVisibleItemPosition();
            int                 last          = manager.findLastVisibleItemPosition();
            int                 headViewCount = mPullToRefreshRecyclerView.getHeaderViewCount();
            for (int i = first; i <= last; i++) {
                View view = manager.findViewByPosition(i);
                if (view == null || i == 0) {
                    return;
                }
                ImageView ivStatusLight = (ImageView) view.findViewById(R.id.iv_status_light);
                ((BuildingInspectionCheckItemAdapter) mAdapter).setStatusLight(i - headViewCount, ivStatusLight);
            }
            */
        }
    };

    @Override
    public void onPullRefresh() {
        //mDataList.clear();
        SafeDataServices.init().getCheckItemList(mCompanyBuildingItemCountVo.getBuildingId(), mCompanyBuildingItemCountVo.getFloorNumber(), mCompanyBuildingItemCountVo.getPositionMark(), mKeyWord);
        try {
            mHUDUtil.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 数据请求事件
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(HttpCallbackEvent<CompanyBuildingCheckItemExistVo> event) {

        if (EventTag.TAG_SAFE_DATA_COLLECTION_BUILDING_CHECK_ITEM_LIST.equals(event.getTag())) {
            try {
                mHUDUtil.hidden();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                RefreshType type = (RefreshType) event.getOther();
                if (RefreshType.REFRESH == type) {
                    mPullToRefreshRecyclerView.onRefreshComplete();
                }
                if (Constants.Result.SUCCESS == event.getEventResult()) {
                    if (RefreshType.REFRESH == type) {
                        httpRefresh(event.getObj().getItemlist());
                    }
                    currentPage++;
                } else if (Constants.Result.ERROR == event.getEventResult()) {
                    if (RefreshType.REFRESH == type) {
                        httpRefreshError(event.getMsg());
                    }
                }
            }
        } else if (EventTag.TAG_SAFE_DATA_COLLECTION_BUILDING_CHECK_ITEM_DELETE_ACTION.equals(event.getTag())) {
            try {
                mHUDUtil.hidden();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                mHUDUtil.showHUD();
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                if (Constants.Result.SUCCESS == event.getEventResult()) {
                    mHUDUtil.showDoneTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            //mPullToRefreshRecyclerView.beginRefreshing();
                            onPullRefresh();
                        }
                    });
                } else if (Constants.Result.ERROR == event.getEventResult()) {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        }
    }


    public void httpRefresh(List<CompanyBuildingCheckItemVo> data) {
        if (data != null && !data.isEmpty()) {
            mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
            if (data.size() < pageSize) {
                mPullToRefreshRecyclerView.setRefreshMode(Mode.DISABLED);
            } else {
                mPullToRefreshRecyclerView.setRefreshMode(Mode.DISABLED);
            }
            mDataList.clear();
            mAdapter.notifyDataSetChanged();
            mAdapter.addItems(data);
        } else {
            mMultiStateView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
        }
    }


    public void httpRefreshError(String msg) {
        mHUDUtil.showErrorTip(msg);
        mMultiStateView.setViewState(MultiStateView.VIEW_STATE_ERROR);
    }


    /**
     * 刷新事件
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(BuildingCheckItemRefreshEvent event) {
        if (BuildingCheckItemRefreshEvent.class.getName().equals(event.getTag())) {
            //mPullToRefreshRecyclerView.beginRefreshing();
            onPullRefresh();

            try {
                BuildingPositionRefreshEvent refreshEvent = new BuildingPositionRefreshEvent();
                refreshEvent.setTag(BuildingPositionRefreshEvent.class.getName());
                AppService.getBus().post(refreshEvent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 查看详情
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(InspectionCheckItemViewDetailEvent event) {
        if (InspectionCheckItemViewDetailEvent.class.getName().equals(event.getTag())) {
            Bundle bundle = new Bundle();
            bundle.putSerializable(BundleKey.COMPANY_BUILD_INFO, mCompanyBuildingVo);
            bundle.putSerializable(BundleKey.COMPANY_BUILDING_ITEM_COUNT, mCompanyBuildingItemCountVo);
            bundle.putSerializable(BundleKey.COMPANY_BUILDING_INDEX_VO, mCompanyBuildingIndexVo);
            bundle.putSerializable(BundleKey.COMPANY_BUILDING_CHECK_ITEM_VO, event.getData());
            UIHelper.showActivity(getContext(), bundle, CheckItemDetailActivity.class);
        }
    }

    /**
     * 进入检查
     *
     * @param data
     * @param position
     */
    @Override
    public void onItemClick(CompanyBuildingCheckItemVo data, int position) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(BundleKey.COMPANY_BUILD_INFO, mCompanyBuildingVo);
        bundle.putSerializable(BundleKey.COMPANY_BUILDING_ITEM_COUNT, mCompanyBuildingItemCountVo);
        bundle.putSerializable(BundleKey.COMPANY_BUILDING_INDEX_VO, mCompanyBuildingIndexVo);
        bundle.putSerializable(BundleKey.COMPANY_BUILDING_CHECK_ITEM_VO, data);
        UIHelper.showActivity(getContext(), bundle, SafeInspectionStepOneActivity.class);
    }


}
